﻿// description  : 业务核心领域模型
// author       : tristan
// created      : 2011/2/17
// contact      : snaprack@gmail.com


namespace RBAC
{

    using System;
    using System.Linq;
    using System.Linq.Expressions;
    using System.Data.SqlClient;

    /// <summary>
    /// 资源
    /// </summary>
    public partial class Resource
    {
        /// <summary>
        /// 获得实体容器
        /// </summary>
        public EntityContext GetEntityContext()
        {
            return EntityContext.GetInstance();
        }
        /// <summary>
        /// 载入资源实例
        /// </summary>
        /// <param name="id">资源标识</param>
        public static Resource Load(string id)
        {
            return Find(role => role.ID == id).FirstOrDefault();
        }
        /// <summary>
        /// 载入所有的资源实例
        /// </summary>
        public static IQueryable<Resource> LoadAll()
        {
            Resource role = new Resource();
            return role.GetEntityContext().Resources;
        }
        /// <summary>
        /// 查询资源实例
        /// </summary>
        /// <param name="predicate">查询条件</param>
        public static IQueryable<Resource> Find(Expression<Func<Resource, bool>> predicate)
        {
            Resource role = new Resource();
            return role.GetEntityContext().Resources.Where(predicate);
        }
        /// <summary>
        /// 添加资源
        /// </summary>
        public void Add()
        {
            GetEntityContext().AddToResources(this);
        }
        /// <summary>
        /// 删除资源
        /// </summary>
        public void Remove()
        {
            GetEntityContext().DeleteObject(this);
        }
        /// <summary>
        /// 保存更改
        /// </summary>
        public void Save()
        {
            try
            {
                GetEntityContext().SaveChanges();
            }
            catch (Exception e)
            {
                Error(e);
            }
        }
        /// <summary>
        /// 处理异常
        /// </summary>
        protected virtual void Error(Exception e)
        {
            Exception baseException = e.GetBaseException();
            if (baseException is SqlException
                && baseException.Message.Contains("违反了 PRIMARY KEY 约束"))
            {
                throw new AccessControlException("添加失败, 资源已经存在!", baseException);
            }
        }
    }
}